﻿using JinJun.EF.Permission.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace JinJun.EF.Permission.Web.Attributes
{
    public class PermissionAttribute : AuthorizeAttribute  //权限过滤器
    {

        /// <summary>
        /// 判断认证是否通过
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //如果上下文不为空
            if (AdminUserContext.adminContext.AdminUser!= null && httpContext.Session != null)
            {
                return true;
            }
            return false;
        }


        /// <summary>
        ///认证不通过的时候所做的操作
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //获取用户请求的地址
            string path = filterContext.HttpContext.Request.Path;

            //自定义路由跳转
            Dictionary<string, object> keys = new Dictionary<string, object>();
            keys.Add("Controller", "Home");
            keys.Add("Action", "Login");
            keys.Add("ReturnUrl", path);
            var routeValue = new RouteValueDictionary(keys);

            //根据指定路由跳转
            filterContext.Result = new RedirectToRouteResult(routeValue);

        }
    }
}